#ifndef _H_tradeapi_H_
#define _H_tradeapi_H_

#include "XServerHandler.h"
#include "CTPSessionApi.h"
//#include "JsonHelper.h"
#include <boost/thread.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/atomic.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>

class tradeapi;

class ctp_session : public CTPSessionSpi
{
public:
	ctp_session(tradeapi& srv, x_size_t peer);
	~ctp_session();

	void handle_close();

	x_int_t handle_work_packet(const x_char_t* recv_data, const x_size_t recv_len
		, x_char_t*& send_data, x_size_t& send_len);

	x_int_t on_handle_work_packet(const x_char_t* recv_data, const x_size_t recv_len
		, x_char_t*& send_data, x_size_t& send_len, bool is_last);

	virtual void OnRecv(const std::string& data);
	virtual void OnClose();

private:
	tradeapi& server_;
	x_size_t peer_;
	CTPSessionApi* ctp_;
};
typedef boost::shared_ptr<ctp_session> ctp_session_ptr;
typedef boost::weak_ptr<ctp_session> ctp_session_weak_ptr;

class tradeapi 
	: public XServerHandlerSpi
{
private:
	XServerHandlerApi* api_ = nullptr;
	boost::unordered_map<x_size_t, ctp_session_ptr> session_map_;
	boost::shared_mutex	session_mutex_;
public:
	tradeapi(XServerHandlerApi* api);

	inline XServerHandlerApi* api() {
		return api_;
	}

	ctp_session_ptr get_peer(const x_size_t peer);

	void handle_close(const x_size_t peer);

	void handle_io_accept(const x_size_t peer);

	x_int_t handle_work_packet(const x_size_t peer, const x_char_t* recv_data, const x_size_t recv_len
		, x_char_t*& send_data, x_size_t& send_len);

	x_int_t on_handle_work_packet(const x_size_t peer, const x_char_t* recv_data, const x_size_t recv_len
		, x_char_t*& send_data, x_size_t& send_len, bool is_last);

};

#endif//_H_tradeapi_H_
